<template>
  <div class="broad-fixed">
    <div class="broad-main">
      <div style="flex-grow: 1; text-align: left">
        <div class="ab_tp_title">
          <img src="../../static/image/word/app_release.png" class="title_img" style="width: 24px; height: 24px; margin=right: 10px" />
          <div>发布广播</div>
        </div>
      </div>
    </div>
    <div class="broad-menu">
      <div>
        <div class="menu-header">类&nbsp;型</div>
        <div class="menu-main">
          <el-radio-group v-model="aType">
            <el-radio label="1"><span style="font-size: 12px; color: #333333">广播通知</span>
            </el-radio>
            <el-radio label="0"><span style="font-size: 12px; color: #333333">系统公告</span>
            </el-radio>
          </el-radio-group>
        </div>
      </div>

      <div v-if="aType == '1'">
        <div class="menu-header">接收人</div>
        <div class="menu-main">
          <template v-for="(item, index) in list">
            {{ index == 0 ? "" : "、" }}{{ item.name }}
          </template>
          <div @click="getUser" class="menu-last"></div>
        </div>
      </div>
      <div v-if="aType == '0'">
        <div class="menu-header">失效期</div>
        <div class="menu-main">
          <!-- <div class="expireTimeBox" v-if="aType == '0'" style="display: inline-block;width:100%"> -->
          <el-date-picker v-model="expireTime" type="datetime" placeholder="选择结束日期时间" prefix-icon="none" value-format="yyyy-MM-dd HH:mm:ss" :default-value="new Date()" size="large" :picker-options="pickerOptionsStart">
          </el-date-picker>
          <!-- </div> -->
          <div class="menu-date-last" style="
              background-image: url(../image/home/chat/date-last.png) no-repeat
                center center;
            "></div>
        </div>
      </div>
      <div>
        <div class="menu-header">主题</div>
        <input class="broadtitle_text" type="text" v-model="broadTitle" maxlength="50" />
      </div>
      <div style="
          flex-grow: 1;
          align-items: flex-start;
          flex-direction: column;
          padding-left: 66px;
          position: relative;
        ">
        <div class="menu-header" style="position: absolute; left: 7px; top: 20px">
          内容
        </div>
        <div class="broad_content">
          <textarea name="" placeholder="消息内容..."  id="textarea_val" style="
              resize: none;
              width: 100%;
              border: none;
              text-align-last: left;
              outline: none;
              flex: 1;
              padding: 1em;
            " v-model="textareaValue" @paste="pasteEvent($event)" @keydown="next()"></textarea>
          <div class="add_broad_file" v-show="broadFileList.length < 10">
            <div class="add_file_icon"></div>
            添加附件
            <input type="file" @change="addBroadFile" id="broadFile" />
          </div>
          <div class="broad_file">
            <div class="broad_file_item" v-for="(item, index) in broadFileList" :key="index + '_bfile'">
              <div class="broad_file_icon"></div>
              {{ item ? item.fileName : "" }}
              <span @click="broadFileList.splice(i, 1)">删除</span>
            </div>
          </div>
        </div>
        <div style="margin-bottom: 3em; margin-top: 10px">
          <Button style="background-color: #f59331; color: #ffffff" @click.native="sendBroad">发送</Button>
          <Button v-if="broadTitle != '' || textareaValue != ''" style="margin-left: 1em" @click.native="sendCancel">清空</Button>
        </div>
      </div>
    </div>
    <Modal v-model="broad_sure" title="发送广播确认" :loading="loading" @on-ok="asyncOK">
      <p>确认发送消息吗？</p>
    </Modal>
    <div class="broad_send_bg" v-if="broadSendLoading"></div>
  </div>
</template>

<script>
import { mapState } from "vuex";
export default {
  name: "broad-send",
  props: ["list", "ws", "toInfo", "broadSendShow", "broadSendAct"],

  data() {
    return {
      broadSendLoading: false,
      width: "70em",
      height: "45em",
      full: true,
      broadTitle: "",
      textareaValue: "",
      broad_sure: false,
      loading: true,
      broadFile: null,
      broadFileList: [],
      attachsize: "",
      attach: "",
      attachName: "",
      aType: "1",
      expireTime: "",
      pickerOptionsStart: {
        disabledDate: (time) => {
          return new Date().getTime() - 24 * 60 * 60 * 1000 > time.getTime();
        },
      },
      //    aType  0:系统公告 1:一般通知
      //    aType =0 时要传expireTime
    };
  },
  computed: {
    ...mapState(["myInfo"]),
  },
  watch: {
    broadSendAct() {
      this.broadFileList = [];
    },

    aType() {
      console.log(this.aType, "广播类型");
    },
  //   textareaValue(newValue) {
  //   this.textareaValue = this.processTextareaContent(newValue); // 当输入发生改变时更新处理后的文本内容
  // }
  },
  methods: {
    next(){
      if(window.event.keyCode==13){
        // textareaValue=vextText+"\n";
        let vextText=$("#textarea_val").val();
        $("#textarea_val").val(vextText+"\n");
      }
    },
    //重写换行
    processTextareaContent(content) {
    return content.replace(/[\r\n]/g, '\n'); // 将所有的回车和换行符替换成换行符
    },
    //复制粘贴板信息
    pasteEvent(e) {
      var _this = this;
      e.preventDefault();
      let infs = this.$shell("GetClipboardData", []);
      infs = eval("(" + infs + ")");
      if (infs.return_code === "TRUE") {
        //判断文件大小是否超过500M，超过后无法发送
        this.$fileBigChoice(infs.return_data.data);
        if (infs.return_data.formats == "Text") {
          document.execCommand(
            "insertHTML",
            false,
            this.$utilJs.returnBrNbsp(
              this.htmlEncodeByRegExp(infs.return_data.data)
            )
          );
          // this.insertContent(this.toExpression(this.returnBrNbsp(this.htmlEncodeByRegExp(infs.return_data.data))));
        }
      }
    },
    // html编码
    htmlEncodeByRegExp(html) {
      var temp = document.createElement("div");
      temp.textContent != undefined
        ? (temp.textContent = html)
        : (temp.innerText = html);
      var output = temp.innerHTML;
      temp = null;
      return output;
    },
    addBroadFile(e) {
      let _this = this;
      let toinfo = this.toInfo;
      let fileInfo = e.target.files[0];
      let filesize = fileInfo.size / 1024 / 1024 || 0;
      if (filesize > 500) {
        this.$Message.warning("发送文件大小不能大于500M");
        return;
      }
      let fileReader = new FileReader();
      fileReader.onload = function (w) {
        document.getElementById("broadFile").value = "";
        let form = _this.$utilJs.get_2_data(
          fileInfo,
          _this.myInfo.id,
          fileInfo.name
        );
        console.log("fileInfo.name", fileInfo.name);
        _this.broadFileList.push({
          form: form,
          fileName: fileInfo.name,
        });
      };
      fileReader.readAsDataURL(fileInfo);
    },
    sendCancel() {
      this.broadTitle = "";
      this.textareaValue = "";
      this.broadFileList = []
      this.expireTime = ""
      this.$emit("sendCancel");
    },
    uploadBroad(item, arr, str, index) {
      return new Promise((resolve, reject) => {
        let newTime = new Date().getTime();
        console.log("上传广播附件", item);
        this.$upload(
          "api/v1/oim/file/upload.do?times=" + parseInt(newTime) + index,
          item.form,
          (info) => {
            if (info.result == 200) {
              this.attachsize += info.data.size + ",";
              this.attach += info.data.id + ",";
              this.attachName += item.fileName + ",";
              if (index == this.broadFileList.length - 1) {
                this.attachsize = this.attachsize.replace(/\,$/, "");
                this.attach = this.attach.replace(/\,$/, "");
                this.attachName = this.attachName.replace(/\,$/, "");
                this.broadSendLoading = false;
                let obj = this.$socketBody(
                  {
                    title: this.broadTitle,
                    content: this.textareaValue,
                    userId: this.$store.state.myInfo.id,
                    members: JSON.stringify(arr),
                    attachsize: this.attachsize,
                    attach: this.attach,
                    attachName: this.attachName,
                    sendUserName: this.myInfo.id,
                    aType: this.aType,
                    expireTime: this.aType == 0 ? this.expireTime : "",
                  },
                  "text",
                  str,
                  newTime
                );
                this.ws.send(
                  this.$radioMessage(
                    this.$func.uuid(),
                    "1.501",
                    "1.1.0001",
                    obj,
                    newTime
                  )
                );
                this.$emit("resetModalFirst");
              }
              resolve();
            } else {
              this.$Message.warning("文件上传失败,请重新发送");
              this.broadSendLoading = false;
              return;
              reject();
            }
          },
          (err) => {
            this.$Message.warning("服务器出错,稍后再试1");
            this.broadSendLoading = false;
            reject();
          }
        );
      });
    },
    asyncOK() {
      console.log(this.expireTime, "结束时间");
      let regn = /\n/g;
      let regs = /\s/g;
      let arr = [];
      let str = this.textareaValue.replace(regn, "<br>");
      // 2022/7/14 新增 对零宽字符判断避免换行出现?号
      // str = str.replace(/\u200B/g,'')
      let _this = this;
      str = str.replace(regs, "&nbsp;&nbsp;");
      for (let i in this.list) {
        arr.push(this.list[i]);
      }
      arr.push({
        type: "0",
        value: this.$store.state.myInfo.id,
      });
      this.attachsize = "";
      this.attach = "";
      this.attachName = "";
      if (this.broadFileList.length > 0) {
        this.broadSendLoading = true;
        async function asyncSendBroad() {
          for (let i = 0; i < _this.broadFileList.length; i++) {
            await _this
              .uploadBroad(_this.broadFileList[i], arr, str, i)
              .catch((err) => {
                return;
              });
          }
        }
        asyncSendBroad();
      } else {
        let newTime = new Date().getTime();
        let obj = this.$socketBody(
          {
            title: this.broadTitle,
            userId: this.$store.state.myInfo.id,
            sendUserName: this.$store.state.myInfo.name,
            head: this.$store.state.myInfo.head,
            gender: this.$store.state.myInfo.gender,
            members: JSON.stringify(arr),
            attachsize: 0,
            attach: "",
            attachName: "",
            aType: this.aType,
            expireTime: this.expireTime,
          },
          "text",
          str,
          newTime
        );
        this.ws.send(
          this.$radioMessage(
            this.$func.uuid(),
            "1.501",
            "1.1.0001",
            obj,
            newTime
          )
        );
        this.$emit("resetModalFirst");
      }
      setTimeout(() => {
        this.broad_hidden();
      }, 1000);
    },
    headerClick(index) {
      if (index == 1 || index == 2) {
        this.full = !this.full;
        this.width = index == 1 ? "100%" : "70em";
        this.height = index == 1 ? "100%" : "45em";
      } else if (index == 3) {
        this.$emit("setClose", 5);
      }
    },
    broad_hidden() {
      console.log("关闭广播确认框");
      this.broad_sure = false;
    },
    getUser() {
      this.$emit("setModalFirst", 1);
    },
    sendBroad() {
      // debugger
      console.log("发送广播");
      if (this.broadTitle == "") {
        this.$Message.warning("请输入主题");
        return;
      }
      if (this.aType == "1") {
        if (this.list.length == 0) {
          this.$Message.warning("请选择发送对象");
          return;
        }
      }
      if (this.textareaValue == "") {
        this.$Message.warning("请输入内容");
        return;
      }
      if (this.aType == "0") {
        if (this.expireTime == "") {
          this.$Message.warning("请输入结束时间");
          return;
        }
      }
      this.broad_sure = true;
    },
  },
};
</script>
<style lang="less" scoped>
.ab_tp_title {
  display: flex;
  align-items: center;
  padding: 1px 20px 10px;
  font-size: 16px;
  font-weight: bold;
  flex-shrink: 0;
  background-repeat: no-repeat;
  background-position: right top;
  div {
    font-size: 16px;
  }
  & > img {
    width: 24px;
    height: 24px;
    margin-right: 1em;
  }
}
</style>
